﻿using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Utilities
{
    public class TraceWrapper
    {
        private TextWriterTraceListener m_traceListener;
        private FileStream m_traceLog;

        public void initTraceListener()
        {
            m_traceLog = new FileStream(Utilities.Path.logPath, FileMode.Append);
            m_traceListener = new TextWriterTraceListener(m_traceLog);
            Trace.Listeners.Add(m_traceListener);
        }

        public void shutdownTraceListener()
        {
            Trace.Flush();
            m_traceLog.Close();
            Trace.Listeners.Remove(m_traceListener);
        }

        public static void LogException(string msg, Exception e)
        {
            Trace.WriteLine("[" + DateTime.Now.ToString("HH:mm:ss:ffff", System.Globalization.CultureInfo.InvariantCulture) + "] - " + msg);
            Trace.WriteLine("");
            Trace.WriteLine("Stack is: " + e.StackTrace);
            Trace.Flush();
        }

        public static void LogCurrentStack()
        {
            Trace.WriteLine("");
            StackTrace st = new StackTrace(true);
            for (int i = 0; i < st.FrameCount; i++)
            {
                // Note that high up the call stack, there is only
                // one stack frame.
                StackFrame sf = st.GetFrame(i);
                Trace.Indent();
                Trace.WriteLine("Method: " + sf.GetMethod().ToString() + ",Line : " + sf.GetFileLineNumber().ToString());
            }

            for (int i = 0; i < st.FrameCount; i++)
                Trace.Unindent();
        }
    }
}
